package com.example.library_demo.aspect;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.library_demo.common.Result;
import com.example.library_demo.entity.User;
import com.example.library_demo.enums.GlobalResponseResultEnum;
import com.example.library_demo.exception.BizException;
import com.example.library_demo.service.IUserService;
import com.example.library_demo.util.HttpServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class AuthAspect {

    @Autowired
    private IUserService userService;

    @Pointcut("@annotation(com.example.library_demo.annotation.Auth)")
    public void pointcut() {
    }

    @Before(value = "pointcut()")
    public void before(JoinPoint joinPoint) {
        HttpServletRequest request = HttpServletUtil.getRequest();
        String token;
        try{
            token = request.getHeader("token");
            User user = userService.getUserByToken(token);
            if (null == user) {
                throw new BizException(GlobalResponseResultEnum.LOSE_AUTH_TOKEN_ERROR);
            }
        }catch (Exception e){
            token = request.getHeader("mtoken");
            if (StringUtils.isEmpty(token)) {
                throw new BizException("登陆后才能操作哦~");
            }
        }
    }


}
